<?php
/**
 * 菜动期数逻辑模块
 * User：LLW
 * Date：2020-04-08
 * Time：14：13
 */

namespace app\api\model;

use think\Db;
use think\Model;
use think\response\Json;
use think\Session;

class RaiseModel extends Model
{
    protected $table = 'cd_raise';

    /**
     * 菜洞期数
     * @return Json
     */
    public function getList()
    {
        $uid = Session::get('uid');
        $type = input('post.type');
        $where['ra_state'] = $type == 1 ? 1 : 2;
        $list = $this->where($where)->order('ra_nper desc')->select();
        foreach ($list as $key=>$val){
            if($val['ra_part'] == 0 || $val['ra_num'] == 0){
                $list[$key]['rate'] = 0;
            }else{
                $list[$key]['rate'] = round(bcmul(bcdiv($val['ra_part'],$val['ra_num'],2),100));
            }
            $list[$key]['ra_atime'] = date('Y-m-d H:i:s',$val['ra_atime']);
            $list[$key]['ra_ltime'] = date('Y-m-d H:i:s',$val['ra_ltime']);
            $type = Db::name('raise_user')->where(['ru_uid'=>$uid,'ru_raid'=>$val['ra_id']])->find();
            if(empty($type)){
                $list[$key]['state'] = 0;
            }elseif ($type['ru_state'] == 0){
                $list[$key]['state'] = 1;
            }else{
                $list[$key]['state'] = 2;
            }
        }
        AjaxReturn(1,'ok',$list);
    }

    /**
     * 众筹分红
     * @return Json
     */
    public function getCast()
    {
        //获取相关数据
        $id = input('post.id');
        $uid = Session::get('uid');
        $Mci = tpConfig('Mci');
        $find = Db::name('user')->where('us_uid',$uid)->find();
        $raise = $this->where('ra_id',$id)->find();
        $rase_user = Db::name('raise_user')->where(['ru_uid'=>$uid,'ru_raid'=>$id])->find();
        //验证数据
        if($find['us_points'] < $Mci){
            AjaxReturn(-1,'账户可用资产不足，请先去充值');
        }
        if(!empty($rase_user)){
            AjaxReturn(-1,'您已经参与过此期众筹了');
        }
        if(empty($raise)){
            AjaxReturn(-1,'本期众筹已结束，请期待下一期的发布');
        }
        if($raise['ra_state'] == 4){
            AjaxReturn(-1,'本期众筹暂未开启');
        }
        if($raise['ra_state'] == 2){
            AjaxReturn(-1,'本期众筹已结束，请期待下一期的发布');
        }
        $data['ru_uid'] = $uid;
        $data['ru_money'] = $Mci;
        $data['ru_raid'] = $id;
        $data['ru_time'] = time();
        //扣除余额
        $res = Db::name('raise_user')->insert($data);
        if($res){
            //扣除余额加入锁仓
            accountMoneyLog($uid,-$Mci,'参与第'.$raise['ra_nper'].'期众筹扣除',$Mci);
//            Db::name('user')->where('us_uid',$uid)->setInc('us_lock_cabin',$Mci);
            $this->where('ra_id',$id)->setInc('ra_part',1);//参与人数+1
            catUp($find['us_pid'],1,$Mci,$raise['ra_nper']);//上级拿奖励

            //二期之后的众筹进行奖金分红
            if($raise['ra_part']+1 >= $raise['ra_num']) {
                //众筹期数转变为完成
                $this->where('ra_id',$id)->setField('ra_state',2);
                //开始下一期的众筹
                $raise_dei = $this->where(['ra_nper'=>$raise['ra_nper']+1,'ra_state'=>4])->setField('ra_state',1);
                if(!$raise_dei){
                    //不存在的话则执行最新的众筹
                    $raise_fen = $this->where(['ra_state'=>4])->order('ra_nper asc')->select();
                    if(!empty($raise)){
                        $raise_pei = $this->where(['ra_id'=>$raise_fen[0]['ra_id']])->setField('ra_state',1);
                    }
                }
                if($raise['ra_nper'] > 3){
                    $this->getMoney($raise['ra_nper']-3);
                }
            }
            AjaxReturn(1,'参与成功');
        }
        AjaxReturn(-1,'哎呀，网络好像出现些小波动');
    }

    /**
     * 众筹分红
     * @param $nper  需分红的期数
     * @return bool
     */
    public function getMoney($nper)
    {
        //获取相关数据
        $find = $this->where('ra_nper',$nper)->find();
        $conf = bcdiv(tpConfig("static"),100,4);
        $list = Db::name('raise_user')
            ->alias('r')
            ->join('cd_raise s','r.ru_raid=s.ra_id')
            ->where(['ru_raid'=>$find['ra_id'],'ru_state'=>0,'ra_state'=>2])
            ->field('r.*,s.ra_nper')
            ->select();

        //数据操作
        foreach ($list as $v){
            //获得奖励次数+1
            $user = Db::name('user')->where('us_uid',$v['ru_uid'])->setInc('us_reward',1);
            $reward = Db::name('user')->where('us_uid',$v['ru_uid'])->value('us_reward');

            //计算利息
            $sart = bcmul($v['ru_money'],bcmul($conf,$reward,2),4);
            //计算总额
            $money = bcadd($v['ru_money'],$sart,4);
            //分红
            Db::name('raise_user')->where('ru_id',$v['ru_id'])->setField('ru_state',1);
            accountMoneyLog($v['ru_uid'],$money,'第'.$v['ra_nper'].'期结算获得');
        }
        return true;
    }

    /**
     * 投期逻辑
     * @return Json
     */
    public function getRaiseUser()
    {
        $uid = Session::get('uid');
        $list = Db::name('raise_user')->alias('r')
            ->join('cd_raise e','r.ru_raid=e.ra_id')
            ->where('ru_uid',$uid)
            ->order('ra_nper asc')
            ->select();
        foreach ($list as $key=>$val){
            if($val['ra_part'] == 0 || $val['ra_num'] == 0){
                $list[$key]['rate'] = 0;
            }else{
                $list[$key]['rate'] = round(bcdiv($val['ra_num'],$val['ra_part'],2));
            }
            $list[$key]['ra_atime'] = date('Y-m-d H:i:s',$val['ra_atime']);
            $list[$key]['ra_ltime'] = date('Y-m-d H:i:s',$val['ra_ltime']);
            $list[$key]['ru_time'] = date('Y-m-d H:i:s',$val['ru_time']);
        }
        AjaxReturn(1,'ok',$list);
    }

    /**
     * 提币逻辑
     * @return Json
     */
    public function getMoneyTi()
    {
        $data = input('post.');
        $uid = Session::get('uid');
        $find = Db::name('user')->where('us_uid',$uid)->find();
        $data['ca_batch'] = time().rand_number(6);
        $data['ca_atime'] = time();
        $data['ca_uid'] = $uid;
        if(empty($find['us_closed_code']) && empty($find['us_closed_code'])){
            AjaxReturn(-1,'请先去个人信息页面完善收款信息');
        }
        if($data['us_pwds'] != $find['us_pwds']){
            AjaxReturn(-1,'密钥不正确');
        }
        if($find['us_points'] < $data['ca_money']){
            AjaxReturn(-1,'余额不足');
        }
        $res = Db::name('cash')->insert($data);
        if($res){
            accountMoneyLog($uid,$data['ca_money'],'会员自主提现');
            AjaxReturn(1,'申请成功');
        }else{
            AjaxReturn(-1,'申请失败');
        }
    }

    /**
     * 充币逻辑
     * @return Json
     */
    public function getMoneyCb()
    {
        $data = input('post.');
        $uid = Session::get('uid');
        $data['ct_batch'] = time().rand_number(6);
        $data['ct_time'] = time();
        $data['ct_uid'] = $uid;
        $res = Db::name('cash_type')->insert($data);
        if($res){
            AjaxReturn(1,'充值成功，等待审核');
        }else{
            AjaxReturn(-1,'充值失败');
        }
    }
}